"""
用户数据模型
"""

from sqlalchemy import Column, Integer, String, DateTime, Boolean, Text
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship

from app.database import Base


class User(Base):
    """用户表"""
    __tablename__ = "users"

    # 基础字段
    id = Column(Integer, primary_key=True, index=True, comment="用户ID")
    email = Column(String(191), unique=True, index=True, nullable=False, comment="邮箱地址")  # 191字符适配utf8mb4索引限制
    hashed_password = Column(String(255), nullable=False, comment="加密密码")
    
    # 用户信息
    nickname = Column(String(100), nullable=True, comment="用户昵称")
    avatar_url = Column(String(500), nullable=True, comment="头像URL")
    
    # 状态字段
    is_active = Column(Boolean, default=True, comment="是否激活")
    is_verified = Column(Boolean, default=False, comment="邮箱是否验证")
    is_superuser = Column(Boolean, default=False, comment="是否超级用户")
    
    # 时间字段
    created_at = Column(DateTime(timezone=True), server_default=func.now(), comment="创建时间")
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), comment="更新时间")
    last_login_at = Column(DateTime(timezone=True), nullable=True, comment="最后登录时间")
    
    # 验证相关
    email_verification_token = Column(String(255), nullable=True, comment="邮箱验证令牌")
    email_verification_expires = Column(DateTime(timezone=True), nullable=True, comment="验证令牌过期时间")
    
    # 密码重置
    reset_password_token = Column(String(255), nullable=True, comment="密码重置令牌")
    reset_password_expires = Column(DateTime(timezone=True), nullable=True, comment="重置令牌过期时间")
    
    # 用户设置
    notification_email = Column(Boolean, default=True, comment="是否接收邮件通知")
    notification_wechat = Column(Boolean, default=False, comment="是否接收微信通知")
    timezone = Column(String(50), default="Asia/Shanghai", comment="用户时区")
    
    # 通知渠道设置
    channel = Column(String(20), default="EMAIL", comment="通知渠道：EMAIL/WECHAT/SMS/TG")
    tg = Column(String(50), nullable=True, comment="Telegram用户名或ID")
    openid = Column(String(50), nullable=True, comment="openid")
    
    # 关联关系
    balance = relationship("Balance", back_populates="user", uselist=False, cascade="all, delete-orphan")
    balance_transactions = relationship("BalanceTransaction", back_populates="user", cascade="all, delete-orphan")
    monitors = relationship("Monitor", back_populates="user", cascade="all, delete-orphan")
    notify_logs = relationship("NotifyLog", back_populates="user", cascade="all, delete-orphan")
    product_notifications = relationship("ProductNotification", back_populates="user", cascade="all, delete-orphan")
    notifications = relationship("Notification", back_populates="user", cascade="all, delete-orphan")

    def __repr__(self):
        return f"<User(id={self.id}, email='{self.email}')>"

    @property
    def current_balance(self):
        """获取当前余额"""
        if self.balance:
            return self.balance.amount
        return 0

    @property
    def active_monitors_count(self):
        """获取活跃监控数量"""
        return len([m for m in self.monitors if m.is_active])

    def can_create_monitor(self):
        """检查是否可以创建监控（余额是否充足）"""
        return self.current_balance >= 1
